/**
 * 纵向对比图表组件（可复用）
 */

import React from 'react';
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, ArcElement, Title, Tooltip, Legend, RadialLinearScale, PointElement, LineElement, Filler } from 'chart.js';
import { Bar, Pie, Doughnut, Radar } from 'react-chartjs-2';

ChartJS.register(CategoryScale, LinearScale, BarElement, ArcElement, Title, Tooltip, Legend);
ChartJS.register(RadialLinearScale, PointElement, LineElement, Filler);

interface VerticalComparisonChartProps {
  data: {
    labels: string[];
    datasets: Array<{
      label: string;
      data: number[];
      backgroundColor?: string | string[];
      borderColor?: string | string[];
      borderWidth?: number;
      type: string;
      stack?: string;
    }>;
  };
  options?: any;
  height?: number;
}

const VerticalComparisonChart: React.FC<VerticalComparisonChartProps> = ({ data, options, height = 400 }) => {
  const chartType = data.datasets[0]?.type || 'bar';
  const chartData = {
    labels: data.labels,
    datasets: data.datasets.map(dataset => ({
      label: dataset.label,
      data: dataset.data,
      backgroundColor: dataset.backgroundColor,
      borderColor: dataset.borderColor,
      borderWidth: dataset.borderWidth || 2,
      stack: dataset.stack,
      // 雷达图默认填充半透明区域
      fill: (chartType === 'radar') ? true : (dataset as any).fill,
    })),
  } as any;

  const defaultOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: { position: 'top' as const, labels: { usePointStyle: true, padding: 15, font: { size: 12 } } },
      tooltip: {
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        padding: 12,
        titleFont: { size: 14 },
        bodyFont: { size: 12 },
        callbacks: {
          label: function(context: any) {
            let label = context.dataset.label || '';
            if (label) label += ': ';
            if (context.parsed !== null && context.parsed !== undefined) {
              let value: any;
              if (chartType === 'pie' || chartType === 'doughnut') {
                value = context.parsed;
              } else if (chartType === 'radar') {
                value = (context.parsed && (context.parsed.r ?? context.raw)) ?? context.raw;
              } else {
                value = context.parsed.y;
              }
              label += Number((Number(value)).toFixed(2)).toLocaleString();
              if (chartType === 'pie' || chartType === 'doughnut') {
                const total = context.dataset.data.reduce((a: number, b: number) => a + b, 0);
                const percentage = ((value / total) * 100).toFixed(1);
                label += ` (${percentage}%)`;
              }
            }
            return label;
          },
        },
      },
    },
    ...options,
  } as any;

  if (chartType === 'pie') {
    return <div style={{ width: '100%', height: `${height}px`, position: 'relative' }}><Pie data={chartData} options={defaultOptions} /></div>;
  }
  if (chartType === 'doughnut') {
    return <div style={{ width: '100%', height: `${height}px`, position: 'relative' }}><Doughnut data={chartData} options={defaultOptions} /></div>;
  }
  if (chartType === 'radar') {
    const radarOptions = {
      ...defaultOptions,
      scales: {
        r: {
          angleLines: { color: 'rgba(0, 0, 0, 0.05)' },
          grid: { color: 'rgba(0, 0, 0, 0.08)' },
          pointLabels: { font: { size: 12 } },
          ticks: { backdropColor: 'transparent' },
        },
      },
      elements: { line: { borderWidth: 2 } },
    } as any;
    return <div style={{ width: '100%', height: `${height}px`, position: 'relative' }}><Radar data={chartData} options={radarOptions} /></div>;
  }

  const barOptions = {
    ...defaultOptions,
    scales: {
      x: { display: true, stacked: data.datasets.some((ds: any) => ds.stack), title: { display: true, text: '数据系列', font: { size: 12 } }, grid: { display: true, color: 'rgba(0, 0, 0, 0.05)' } },
      y: { display: true, stacked: data.datasets.some((ds: any) => ds.stack), beginAtZero: true, title: { display: true, text: '数值', font: { size: 12 } }, grid: { display: true, color: 'rgba(0, 0, 0, 0.05)' } },
    },
  } as any;

  return <div style={{ width: '100%', height: `${height}px`, position: 'relative' }}><Bar data={chartData} options={barOptions} /></div>;
};

export default VerticalComparisonChart;


